import NetWorkMgr from "../Manager/NetWorkManager";
import { EventTypeConst } from "../Const/EventTypeConst";

export class HttpReq {
    
    public static sendGet(mainurl: string, params?: string, callBack?: (resp: any) => void, tag?: string): void {

        let url:string = mainurl;
        if(params)
        {
            url  = mainurl + "?" + params;
        }
        
        const xhr = new XMLHttpRequest();


        xhr.onerror = () => {
            console.log("onerror " + xhr.statusText);
            
            if(tag)
            {
                NetWorkMgr.sendEvent(EventTypeConst.HTTP_ERROR,tag);
            }

        };
        xhr.onreadystatechange = (() => {

            if (xhr.readyState === 4) {

                if ((xhr.status >= 200 && xhr.status <= 400) || xhr.status === 304) {

                    if(tag)
                    {
                        NetWorkMgr.sendEvent(EventTypeConst.HTTP_SUCCESS,tag);
                    }

                }
            }

        });

        xhr.ontimeout = () => {
            if(tag)
            {
                NetWorkMgr.sendEvent(EventTypeConst.HTTP_TIMEOUT,tag);
            }
        };
        xhr.timeout = 3000;

        xhr.open("GET", url, true);

        xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
        xhr.send();
    }
}